package com.sjx.jtt809.server.business.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.sjx.jtt809.server.business.IBusinessServer;
import com.sjx.jtt809.server.manager.SlaveLinkManagerJtt809;
import com.sjx.jtt809.server.pojo.command.RequestJtt809_0x1002;
import com.sjx.jtt809.server.pojo.command.RequestJtt809_0x1002_Result;
import com.sjx.jtt809.server.pojo.command.ResponseJtt809_0x1001;
import com.sjx.jtt809.server.util.ConstantJtt809Util;
import com.sjx.util.ConstantUtil;
import com.sjx.util.PropsUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;

/**
 * 主链路登录请求消息
 * 链路类型:主链路。
 * 消息方向:下级平台往上级平台。
 * 业务数据类型标识: UP-CONNECT-REQ。
 * 描述:下级平台向上级平台发送用户名和密码等登录信息。
 */
public class ResponseHandlerImpl_0x1001 implements IBusinessServer<ResponseJtt809_0x1001> {

    private static final Log logger = LogFactory.get();

    private static final int USER_ID = PropsUtil.getConfigInstance().getInt(ConstantUtil.JTT809_NETTY_SERVER_USERID);

    private static final String PASSWORD = PropsUtil.getConfigInstance().getStr(ConstantUtil.JTT809_NETTY_SERVER_PASSWORD);

    @Override
    public void businessHandler(ChannelHandlerContext ctx, ResponseJtt809_0x1001 msg) {
        try {
            RequestJtt809_0x1002 jtt8090X1002 = new RequestJtt809_0x1002();

            // 随机生成校验码
            int verifyCode = RandomUtil.randomInt(999999);
            jtt8090X1002.setVerifyCode(verifyCode);

            if (msg.getUserId() != USER_ID) {
                // 用户没有注册
                jtt8090X1002.setResult(RequestJtt809_0x1002_Result.USER_NOT_REGISTERED);
                ctx.writeAndFlush(jtt8090X1002);
            } else if (msg.getUserId() == USER_ID && !StrUtil.equalsIgnoreCase(msg.getPassword(), PASSWORD)) {
                // 密码错误
                jtt8090X1002.setResult(RequestJtt809_0x1002_Result.WRONG_PASSWORD);
                ctx.writeAndFlush(jtt8090X1002);
            } else if (!ReUtil.isMatch(ConstantUtil.REGEX_IS_IP, msg.getDownLinkIp())) {
                // 判断是否为内网ip || NetUtil.isInnerIP(msg.getDownLinkIp())
                // ip地址不正确
                jtt8090X1002.setResult(RequestJtt809_0x1002_Result.IP_ADDRESS_IS_ERROR);

                ctx.writeAndFlush(jtt8090X1002);
            } else if (msg.getMsgGesscenterId() != PropsUtil.getConfigInstance().getInt(ConstantUtil.JTT809_FACTORY_ACCESS_CODE)) {
                // 接入码不正确
                jtt8090X1002.setResult(RequestJtt809_0x1002_Result.ACCESS_CODE_IS_ERROR);

                ctx.writeAndFlush(jtt8090X1002);
            } else {
                // 正确
                jtt8090X1002.setResult(RequestJtt809_0x1002_Result.SCUUESS);
                ctx.writeAndFlush(jtt8090X1002);

                // 延迟0.5s后连接
                Thread.sleep(500);

                // 建立从链路连接
                logger.info("======> 开始建立从链路连接.... 下级平台IP = {}，下级平台Port = {}，随机校验码 = {}", msg.getDownLinkIp(), msg.getDownLinkPort(), verifyCode);
                Channel channel = new SlaveLinkManagerJtt809(msg.getDownLinkIp(), msg.getDownLinkPort(), verifyCode).start();

                // 将上下级平台关联
                InetSocketAddress upRemoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                InetSocketAddress downRemoteAddress = (InetSocketAddress) channel.remoteAddress();
                ConstantJtt809Util.UP_DOWN_PLATFORM_LINK.put(upRemoteAddress.toString(),downRemoteAddress.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
